package com.example.bookshelf;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ActionMode;
import androidx.appcompat.widget.SearchView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;

import com.example.bookshelf.data.BookItem;
import com.example.bookshelf.data.BookManager;
import com.example.bookshelf.data.Bookshelf;
import com.example.bookshelf.data.DataReader;
import com.example.bookshelf.data.HttpDataLoader;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class MainActivity extends AppCompatActivity implements ActionMode.Callback{
    @SuppressLint("StaticFieldLeak")
    public static MainActivity instance;
    private BookManager mBookManage;
    private ArrayList<BookItem> bookItemsShow;
    private ArrayList<BookItem> bookItemsShowTemp;
    private ArrayList<String> spinnerBookshelvesShow;

    private ArrayAdapter<String> arrayAdapterBookshelves;
    private RecyclerViewAdapter recyclerViewAdapter;

    private Toolbar toolbar;
    private Spinner spinnerBookshelf;
    private int selectedBookshelfPosition;

    private ActionMode actionMode;
    public Set<Integer> bookItemCheckedPositionSet = new HashSet<>();



    // activity返回时的数据交互------------------------------------------------------------------------
    @SuppressLint("NotifyDataSetChanged")
    private final ActivityResultLauncher<Intent> inputDataLaunch = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {
                if (null != result) {
                    Intent intent = result.getData();
                    if (result.getResultCode() == EditActivity.RESULT_CODE_SUCCESS) {
                        assert intent != null;
                        Bundle bundle = intent.getExtras();

//                        BookItem bookItem = BookItem.getBookItemFromBundle(bundle);
                        // 更新标签的显示
                        mBookManage.updateBookLabels(bundle.getParcelableArrayList("bookLabels"));
                        // 更新书籍的显示
                        mBookManage.updateBookshelves(bundle.getParcelableArrayList("bookshelves"));
                        initBookshelfSpinner();
                        // 更新显示的书籍
                        BookItem bookItem = bundle.getParcelable("bookItem");
                        bookItemsShow.clear();
                        bookItemsShow.addAll(mBookManage.getAllBooks());
                        bookItemsShow.add(bookItem);
                        mBookManage.getBookItems().add(bookItem);
                        recyclerViewAdapter.notifyDataSetChanged();
                        new DataReader().SaveBookManager(this, mBookManage);
                        Log.v("data", "add book item, now have " + bookItemsShow.size());
                    }

                }
            });

    @SuppressLint("NotifyDataSetChanged")
    private final ActivityResultLauncher<Intent> bookDetailsLaunch = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {
                if(null != result) {
                    Intent intent = result.getData();
                    if (result.getResultCode() == BookDetailsActivity.RESULT_CODE_CHANGED) {
//                        assert intent != null;
                        if (null != intent) {
                            Bundle bundle = intent.getExtras();
                            mBookManage.updateBookLabels(bundle.getParcelableArrayList("bookLabels"));
                            mBookManage.updateBookshelves(bundle.getParcelableArrayList("bookshelves"));
                            initBookshelfSpinner();

                            BookItem bookItem = bundle.getParcelable("bookItem");
                            int position = bundle.getInt("position");

                            bookItemsShow.get(position).upData(bookItem);
                            recyclerViewAdapter.notifyItemChanged(position);

                            new DataReader().SaveBookManager(this, mBookManage);
                        }
                    }
                }
            });

    private final ActivityResultLauncher<Intent> aboutLaunch = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {

            });

    private final ActivityResultLauncher<Intent> settingsLaunch = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(), result -> {

            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        instance = this;
        mBookManage = new DataReader().LoadBookManager(this);
//        mBookManage.getBookLabels().add(new BookLabel("66"));
        bookItemsShow = mBookManage.getAllBooks();
        bookItemsShowTemp = new ArrayList<BookItem>();


        initRecyclerView();             // 初始化RecyclerView
        initBookshelfSpinner();         // 初始化bookshelf的spinner
        initFAB_Add();                  // 初始化悬浮按钮的点击事件
        initNavigationView();           // 初始化抽屉菜单
        initToolBar();                  // 初始化工具栏




        // -----------------------------------------------------------------------------------------

//        new Thread(new Runnable() {
//            @SuppressLint("NotifyDataSetChanged")
//            @Override
//            public void run() {
////                String path = "https://api.jike.xyz/situ/book/isbn/9787020024759?apikey=14514.7966a1e7ba9c727138580c3ae3c5372b.0f1f31512707df7479961f742eab5dff";
////                String res = HttpDataLoader.getHttpData(path);
////                Log.i("123465", "onCreate: " + res);
//                BookItem bookItem = HttpDataLoader.getBookItemByISBN("9787020024759");
//
//                if (null != bookItem) {
//                    MainActivity.this.runOnUiThread((new Runnable() {
//                        @Override
//                        public void run() {
//                            bookItemsShow.add(bookItem);
//                            recyclerViewAdapter.notifyDataSetChanged();
//                        }
//                    }));
//                }
//            }
//        }).start();


    }



    // ##############
    // 获得书架的显示内容
    // ##############
    private ArrayList<String> getSpinnerBookshelvesShow() {
        ArrayList<String> showData = new ArrayList<>();
        for (Bookshelf bookshelf : mBookManage.getBookshelves()) {
            showData.add(bookshelf.getName());
        }

        showData.add(0, "所有");
        return showData;
    }


    // 各种view的初始化-------------------------------------------------------------------------------

    // 布局的初始化-----------------------------------------------------------------------------------
    // ---------------------------------------------------------------------------------------------
    // ################
    // 初始化RecycleView
    // ################
    private void initRecyclerView() {
        RecyclerView mainRecyclerView = findViewById(R.id.recyclerView_main);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mainRecyclerView.setLayoutManager(linearLayoutManager);

        recyclerViewAdapter = new RecyclerViewAdapter(bookItemsShow);

        recyclerViewAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (actionMode != null) {
                    // 如果当前处于多选状态，则进入多选状态的逻辑
                    // 维护当前已选的position
                    addOrRemove(position);

                } else {
                    // 如果不是多选状态，则进入点击事件的业务逻辑
                    // TODO something
                    Intent intent = new Intent(MainActivity.this, BookDetailsActivity.class);
                    Bundle bundle = new Bundle();

                    bundle.putParcelableArrayList("bookshelves", mBookManage.getBookshelves());
                    bundle.putParcelableArrayList("bookLabels", mBookManage.getBookLabels());
                    bundle.putParcelable("bookItem", recyclerViewAdapter.getItem(position));
                    bundle.putInt("position", position);
                    intent.putExtras(bundle);
                    bookDetailsLaunch.launch(intent);
                }
                Log.v("click", "book item is clicked");
            }

            @Override
            public void onItemLongClick(View view, int position) {
                if (actionMode == null) {
                    actionMode = startSupportActionMode(MainActivity.this);
                    addOrRemove(position);
                }
                Log.v("click", "book item is long clicked");
            }
        });


        mainRecyclerView.setAdapter(recyclerViewAdapter);

    }

    // ---------------------------------------------------------------------------------------------
    // #################
    // 初始化书架的spinner
    // #################
    private void initBookshelfSpinner() {
        spinnerBookshelf = findViewById(R.id.spinner_main_bookshelf);
        spinnerBookshelvesShow = getSpinnerBookshelvesShow();
        arrayAdapterBookshelves = new ArrayAdapter<String>(
                this, R.layout.item_spinner, spinnerBookshelvesShow);
        arrayAdapterBookshelves.setDropDownViewResource(R.layout.item_spinner_drow_down);
        spinnerBookshelf.setAdapter(arrayAdapterBookshelves);
        spinnerBookshelf.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String selectedItemName = (String) spinnerBookshelf.getSelectedItem();
                selectedBookshelfPosition = spinnerBookshelf.getSelectedItemPosition();
                if (selectedItemName.equals("所有")) {
                    bookItemsShow.clear();
                    bookItemsShow.addAll(mBookManage.getAllBooks());
                }
                else {
                    bookItemsShow.clear();
                    bookItemsShow.addAll(mBookManage.getBooksByBookshelf(selectedItemName));
                }

                recyclerViewAdapter.notifyDataSetChanged();
                Log.i("click", "onItemSelected: " + bookItemsShow.size() + "  " + selectedItemName);
                Log.i("click", "onItemSelected: " + mBookManage.getBookshelves().size());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    // ---------------------------------------------------------------------------------------------
    // ########################
    // 设置FloatingActionButton
    // ########################
    private void initFAB_Add(){
        FloatingActionButton fab_Add = findViewById(R.id.fab_add);
        fab_Add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, EditActivity.class);
                Bundle bundle = new Bundle();

                bundle.putParcelableArrayList("bookshelves", mBookManage.getBookshelves());
                bundle.putParcelableArrayList("bookLabels", mBookManage.getBookLabels());
                bundle.putInt("mode", EditActivity.MODE_ADD);
                intent.putExtras(bundle);
                inputDataLaunch.launch(intent);
            }
        });

        FloatingActionButton fab_AddByISBN = findViewById(R.id.fab_add_isbn);
        fab_AddByISBN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final EditText editText = new EditText(MainActivity.this);
                AlertDialog.Builder inputDialog = new AlertDialog.Builder(MainActivity.this);

                inputDialog.setTitle("请输入ISBN").setView(editText);
                inputDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        new Thread(new Runnable() {
                            @SuppressLint("NotifyDataSetChanged")
                            @Override
                            public void run() {
                                String isbn = editText.getText().toString();
                                BookItem bookItem = HttpDataLoader.getBookItemByISBN(isbn);

                                MainActivity.this.runOnUiThread((new Runnable() {
                                    @Override
                                    public void run() {
                                        if (null != bookItem) {
                                            bookItemsShow.add(bookItem);
                                            mBookManage.getBookItems().add(bookItem);
                                            new DataReader().SaveBookManager(MainActivity.this, mBookManage);
                                            recyclerViewAdapter.notifyDataSetChanged();
                                        }
                                        else {
                                            Toast.makeText(MainActivity.this ,"添加失败", Toast.LENGTH_LONG).show();
                                        }
                                    }
                                }));
                            }
                        }).start();
                    }
                });
                inputDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                inputDialog.show();
            }
        });
    }

    // ###########
    // 初始化抽屉菜单
    // ###########
    private void initNavigationView() {
        NavigationView navigationView = findViewById(R.id.navigation_main);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.item_nav_about:
                        Intent intent = new Intent(MainActivity.this, AboutActivity.class);
                        aboutLaunch.launch(intent);
                        break;
                    case R.id.item_nav_setting:
                        Intent intent1 = new Intent(MainActivity.this, SettingsActivity.class);
                        settingsLaunch.launch(intent1);
                }
                return false;
            }
        });
    }

    // ##########
    // 初始化工具栏
    // ##########
    private void initToolBar() {
        toolbar = findViewById(R.id.toolbar_main);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DrawerLayout Sidebar = findViewById(R.id.drawerLayout_main);
                Sidebar.openDrawer(GravityCompat.START);
            }
        });
    }



    // toolbar中菜单的设置----------------------------------------------------------------------------
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main_toolbar, menu);


        SearchView searchView = (SearchView) menu.findItem(R.id.item_main_toolbar_search).getActionView();

        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                bookItemsShowTemp.clear();
                bookItemsShowTemp.addAll(bookItemsShow);
            }
        });

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public boolean onQueryTextSubmit(String query) {
                ArrayList<BookItem> bookItems_temp = BookManager.searchBookItem(bookItemsShow, query);
                bookItemsShow.clear();
                bookItemsShow.addAll(bookItems_temp);
                recyclerViewAdapter.notifyDataSetChanged();
                return false;
            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public boolean onQueryTextChange(String newText) {
                ArrayList<BookItem> bookItems_temp = BookManager.searchBookItem(bookItemsShowTemp, newText);
                bookItemsShow.clear();
                bookItemsShow.addAll(bookItems_temp);
                recyclerViewAdapter.notifyDataSetChanged();

                return false;
            }

        });


        return true;
    }

    // #####################
    // toolbar中的菜单的选择按钮
    // #####################
    int codeSortBy;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.item_main_toolbar_sort:
                // 单选框的数据准备--------------------------------------------------------------------
                codeSortBy = -1;
                AlertDialog.Builder selectDlg = new AlertDialog.Builder(MainActivity.this);
                selectDlg.setTitle("排序依据");
                String[] items = {"标题", "作者", "出版社", "出版时间"};
                selectDlg.setSingleChoiceItems(items, -1,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                codeSortBy = i;
                            }
                        });
                selectDlg.setPositiveButton("排序",
                        new DialogInterface.OnClickListener() {
                            @SuppressLint("NotifyDataSetChanged")
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                switch (codeSortBy) {
                                    case 0:
                                        BookManager.sortByTitle(bookItemsShow);
                                        recyclerViewAdapter.notifyDataSetChanged();
                                        break;
                                    case 1:
                                        BookManager.sortByAuthor(bookItemsShow);
                                        recyclerViewAdapter.notifyDataSetChanged();
                                        break;
                                    case 2:
                                        BookManager.sortByPress(bookItemsShow);
                                        recyclerViewAdapter.notifyDataSetChanged();
                                        break;
                                    case 3:
                                        BookManager.sortByPublishedDate(bookItemsShow);
                                        recyclerViewAdapter.notifyDataSetChanged();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        });
                selectDlg.show();
                break;
            case R.id.item_main_toolbar_delete_bookshelf:
                String bookshelfName = (String) spinnerBookshelf.getSelectedItem();
                if (!bookshelfName.equals("所有")) {
                    mBookManage.removeBookshelf(new Bookshelf(bookshelfName));
                    spinnerBookshelvesShow.clear();
                    spinnerBookshelvesShow.addAll(getSpinnerBookshelvesShow());
                    arrayAdapterBookshelves.notifyDataSetChanged();
                    System.out.println(bookshelfName);
                }
                break;
            case R.id.item_main_toolbar_rename_bookshelf:
                String bookshelfNameOld = (String) spinnerBookshelf.getSelectedItem();
                if (!bookshelfNameOld.equals("所有")) {
                    final EditText editText = new EditText(MainActivity.this);
                    editText.setText(bookshelfNameOld);
                    AlertDialog.Builder inputDialog =
                            new AlertDialog.Builder(MainActivity.this);

                    inputDialog.setTitle("请输入新的名字").setView(editText);
                    inputDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    String bookshelfNameNew = editText.getText().toString();
                                    mBookManage.renameBookshelf(bookshelfNameOld, bookshelfNameNew);
                                    initBookshelfSpinner();
                                    spinnerBookshelf.setSelection(selectedBookshelfPosition);
                                    new DataReader().SaveBookManager(MainActivity.this, mBookManage);
                                }
                            });
                    inputDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    });

                    inputDialog.show();
                }
                break;

        }


        return true;
    }


    @SuppressLint("NotifyDataSetChanged")
    private void addOrRemove(int position) {
        if (bookItemCheckedPositionSet.contains(position)) {
            // 如果包含，则撤销选择
            bookItemCheckedPositionSet.remove(position);
        } else {
            // 如果不包含，则添加
            bookItemCheckedPositionSet.add(position);
        }
        if (bookItemCheckedPositionSet.size() == 0) {
            // 如果没有选中任何的item，则退出多选模式
            actionMode.finish();
        } else {
            // 设置ActionMode标题
            actionMode.setTitle(bookItemCheckedPositionSet.size() + " 已选择");
            // 更新列表界面，否则无法显示已选的item
            recyclerViewAdapter.notifyDataSetChanged();
        }
    }



    // ActionMode.Callback接口的实现------------------------------------------------------------------
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        if (actionMode == null) {
            actionMode = mode;
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.menu_main_revise_book, menu);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }

    // ---------------------------------------------------------------------------------------------
    // ###########################
    // 设置Action状态下的menu的点击事件
    // ###########################
    int bookshelfChoice = -1;
    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_main_toolbar_action_delete_book:
                // 删除已选
                Set<BookItem> valueSet = new HashSet<>();
                for (int position : bookItemCheckedPositionSet) {
                    valueSet.add(recyclerViewAdapter.getItem(position));
                }
                for (BookItem val : valueSet) {
                    recyclerViewAdapter.remove(val);
                    mBookManage.getBookItems().remove(val);
                }
                new DataReader().SaveBookManager(this, mBookManage);
                mode.finish();
                return true;
            case R.id.item_main_toolbar_action_set_reading_state:
                String[] items = {getString(R.string.reading_state_unread), getString(R.string.reading_state_reading), getString(R.string.reading_state_readed)};
                AlertDialog.Builder selectBookshelfDlg = new AlertDialog.Builder(MainActivity.this);
                selectBookshelfDlg.setTitle("设置阅读状态");
                selectBookshelfDlg.setSingleChoiceItems(items, -1,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                bookshelfChoice = i;
                            }
                        });
                selectBookshelfDlg.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Set<BookItem> valueSet = new HashSet<>();
                        for (int position : bookItemCheckedPositionSet) {
                            valueSet.add(recyclerViewAdapter.getItem(position));
                        }
                        for (BookItem val : valueSet) {
                            val.setReadingStatus(items[bookshelfChoice]);
                        }
                        new DataReader().SaveBookManager(MainActivity.this, mBookManage);
                        mode.finish();
                    }
                });
                selectBookshelfDlg.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                selectBookshelfDlg.show();
                return true;
            default:
                return false;
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onDestroyActionMode(ActionMode mode) {
        actionMode = null;
        bookItemCheckedPositionSet.clear();
        recyclerViewAdapter.notifyDataSetChanged();
    }

}




class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private OnItemClickListener onItemClickListener;
    private ArrayList<BookItem> bookItems;

    public RecyclerViewAdapter(ArrayList<BookItem> bookItems){
        this.bookItems = bookItems;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_main, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") int position) {

        holder.getTextViewTitle().setText(bookItems.get(position).getTitle());
        holder.getTextViewInfo().setText(bookItems.get(position).getInfo());

        holder.getTextViewDate().setText(bookItems.get(position).getDate());
        holder.getImageViewImage().setImageResource(bookItems.get(position).getImageID());

        holder.setBackground(position);

        LinearLayout linearLayout = holder.getLinearLayout();
        if (onItemClickListener!=null){
            linearLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.onItemClick(v, position);
                }
            });
            linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onItemClickListener.onItemLongClick(v, position);
                    return true;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return bookItems.size();
    }

    @SuppressLint("NotifyDataSetChanged")
    public void remove(BookItem bookItem){
        bookItems.remove(bookItem);
        notifyDataSetChanged();
    }

    public BookItem getItem(int pos){
        return bookItems.get(pos);
    }


    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener{
        void onItemClick(View view, int position);
        void onItemLongClick(View view,int position);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private final ImageView imageViewImage;
        private final TextView textViewTitle;
        private final TextView textViewInfo;
        private final TextView textViewDate;
        private final LinearLayout linearLayout;



        public ImageView getImageViewImage() {
            return imageViewImage;
        }
        public TextView getTextViewTitle() {
            return textViewTitle;
        }
        public TextView getTextViewInfo() {
            return textViewInfo;
        }
        public TextView getTextViewDate() {
            return textViewDate;
        }
        public LinearLayout getLinearLayout() {
            return linearLayout;
        }

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageViewImage = itemView.findViewById(R.id.imageView_item_image);
            textViewTitle = itemView.findViewById(R.id.textView_item_title);
            textViewInfo = itemView.findViewById(R.id.textView_item_info);
            textViewDate = itemView.findViewById(R.id.textView_item_date);
            linearLayout = itemView.findViewById(R.id.linearLayout_main_item);
        }

        @SuppressLint({"ResourceAsColor", "UseCompatLoadingForDrawables"})
        public void setBackground(int position) {
            Set<Integer> positionSet = MainActivity.instance.bookItemCheckedPositionSet;
            if (positionSet.contains(position)) {
                itemView.setBackground(MainActivity.instance.getResources().getDrawable(R.drawable.ic_background_item_selected));
//                itemView.setBackgroundColor(R.color.BackgroundItemCommon);
            } else {
                itemView.setBackground(MainActivity.instance.getResources().getDrawable(R.drawable.ic_background_item_common));
//                itemView.setBackgroundColor(R.color.BackgroundItemCommon);
            }

        }
    }
}
